package com.wusuowei.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wusuowei.ucenter.mapper.SysUserMapper;
import com.wusuowei.ucenter.mapper.SysUserRoleMapper;
import com.wusuowei.ucenter.model.po.SysUser;
import com.wusuowei.ucenter.model.po.SysUserRole;
import com.wusuowei.ucenter.model.vo.PageUserVo;
import com.wusuowei.ucenter.model.vo.UserPasswordVo;
import com.wusuowei.ucenter.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LGY
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleServiceImpl roleService;

    @Override
    public SysUser getUserByPass(String username, String md5Password) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SysUserRole> wrapper2 = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(wrapper.eq(SysUser::getUsername, username).eq(SysUser::getPassword, md5Password));
        if(sysUser !=null){
            List<Integer> rids = sysUserRoleMapper.selectList(wrapper2.eq(SysUserRole::getUserId, sysUser.getId())).stream()
                    .map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRole(roleService.getRoles(String.valueOf(sysUser.getId())));
        }
        return sysUser;
    }

//    @Override
//    public Page<ComUser> findPage(Page<ComUser> page, String username, String email, String address) {
//        return sysUserMapper.findPage(page, username, email, address);
//    }

    @Override
    public void updatePassword(UserPasswordVo userPasswordVo) {
        int update = sysUserMapper.updatePassword(userPasswordVo);
        if (update < 1) {
            throw new RuntimeException("密码错误");
        }
    }

    @Override
    public List<SysUser> findPage(PageUserVo pagequery) {
        return sysUserMapper.findPage(pagequery);
    }

}
